# Copyright 2012 Google Inc. All Rights Reserved.

"""Module containing all open web handlers."""

__author__ = 'pluu@google.com (Phong Luu)'

import os, sys, logging
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'

from google.appengine.dist import use_library
use_library('django', '1.2')

import datetime
import logging
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.ext.webapp import template
from google.appengine.api import memcache
import simplejson
import models
import utils


class APIHandler(webapp.RequestHandler):
  """API handler to return curated videos."""
  def SendJson(self, rows):
    self.response.headers['Content-Type'] = 'application/json; charset=utf-8;'
    self.response.out.write(simplejson.dumps(rows))

  def get(self, org_key):
    page_index = int(self.request.get('page_index', 1))
    tags = filter(None, self.request.get('tags', '').split(','))
    partner = filter(None, self.request.get('partner', '').split(','))
    geo = filter(None, self.request.get('geo', '').split(','))
    q = self.request.get('q', '')

    organization = models.Organization.get(org_key)
    curator = models.Curator(organization)
    curated_content = curator.GetCuratedVideos(
        q=q, tag_list=tags, partners=partner, geo_filters=geo, page_index=page_index)
    self.SendJson(curated_content)


def main():
  application = webapp.WSGIApplication([
      ('/api/video/(.*)/?$', APIHandler)], debug=True)
  util.run_wsgi_app(application)


if __name__ == '__main__':
  main()
